import json,jsonpath
from testcase.ordercenter.conftest import get_ordernum
from testcase.usercenter.conftest import messages_id,get_mobile,get_addressid,get_userfavid,get_userfav_all
from testcase.goodscenter.conftest import get_goodshotsearch,get_goodsid
from common.conmysql import db
# from string import Template
from jinja2 import Template
from common.globalcontenxt import GlobalContext
from common.log import logger

class AsserUtil:
    def __init__(self):
        self.comparators = {
            '>': lambda a, b: a > b,
            '<': lambda a, b: a < b,
            '==': lambda a, b: a == b,
            '>=': lambda a, b: a >= b,
            '<=': lambda a, b: a <= b,
            '!=': lambda a, b: a != b,
        }
    @staticmethod
    def equals(actual_value,expect_value):
        """相等"""
        assert str(actual_value) == expect_value,f"实际结果{actual_value}等于预期结果{expect_value}"

    @staticmethod
    def less_than(actual_value,expect_value):
        """小于"""
        assert actual_value < expect_value, f'{actual_value} < {expect_value})'

    @staticmethod
    def less_than_or_equals(actual_value,expect_value):
        """小于等于"""
        assert actual_value <= expect_value, f'{actual_value} <= {expect_value})'

    @staticmethod
    def greater_than(actual_value,expect_value):
        """大于"""
        assert actual_value > expect_value, f'{actual_value} > {expect_value})'

    @staticmethod
    def greater_than_or_equals(actual_value,expect_value):
        """大于等于"""
        assert actual_value >= expect_value, f'{actual_value} >= {expect_value})'

    @staticmethod
    def not_equals(actual_value,expect_value):
        """不等于"""
        assert actual_value != expect_value, f"{actual_value}!={expect_value}"

    @staticmethod
    def contains(actual_value,expect_value):
        """包含"""
        assert expect_value in actual_value,f"预期结果{expect_value}in实际结果{actual_value}"

    @staticmethod
    def startswith(actual_value,expect_value):
        """以什么开头"""
        assert str(actual_value).startswith(str(expect_value)), f'{str(actual_value)} startswith {str(expect_value)})'

    @staticmethod
    def endswith(actual_value,expect_value):
        """以什么结尾"""
        assert str(actual_value).endswith(str(expect_value)), f'{str(actual_value)} endswith {str(expect_value)})'

    @staticmethod
    def length(actual_value,expect_value):
        """校验数量"""
        if not isinstance(actual_value,list):
            actual_value = [actual_value]
        assert len(actual_value) == expect_value, f'{str(actual_value)} == {str(expect_value)})'


    def expect_by_jsonpath(self,respon_value: dict,expect_expression: str):
        """

        :param respon_value: response.json()
        :param expect_expression: "$.code"
        :return: None或提取第一个值或全部
        """
        expect_value = jsonpath.jsonpath(respon_value,expect_expression)
        if not expect_value:
            return
        elif len(expect_value) == 1:
            return expect_value[0]
        else:
            return expect_value

    def validate_response(self,response,validate_check):
        #校验结果
        for check in validate_check:
            for check_type,check_value in check.items():
                #实际结果
                actual_value = self.expect_by_jsonpath(response,check_value[0])
                #期望结果
                data = check_value[1]
                if not isinstance(data,str):
                    data = str(data)
                if "${" in data and "}" in data:
                    # ${get_ordernum}
                    func_name = data[data.index("$") + 2: data.index("}")]
                    expect_value = eval(func_name + "()")
                else:
                    expect_value = check_value[1]
                if "{{" in data and "}}" in data:
                    expect_value = Template(data).render(GlobalContext().get_showdict())

                # if check_type in self.comparators:
                #     try:
                #         self.comparators[check_type](actual_value,expect_value)
                #     except Exception as e:
                #         raise e
                if check_type in ["eq", "equals", "equal"]:
                    self.equals(actual_value, expect_value)
                elif check_type in ["lt", "less_than"]:
                    self.less_than(actual_value, expect_value)
                elif check_type in ["le", "less_or_equals"]:
                    self.less_than_or_equals(actual_value, expect_value)
                elif check_type in ["gt", "greater_than"]:
                    self.greater_than(actual_value, expect_value)
                elif check_type in ["ne", "not_equal"]:
                    self.not_equals(actual_value, expect_value)
                elif check_type in ["contains"]:
                    self.contains(actual_value, expect_value)
                elif check_type in ["startswith"]:
                    self.startswith(actual_value, expect_value)
                elif check_type in ["endswith"]:
                    self.endswith(actual_value, expect_value)
                elif check_type in ["length"]:
                    self.length(actual_value, expect_value)
                else:
                    print(f'{check_type}  not valid check type')
                logger.info(f"预期结果{expect_value}与实际结果{actual_value}断言成功！")

    from string import Template
    def mysql_validate(self,res,mysql_validate):
        for k,v in mysql_validate.items():
            mysql = v[1]
            dic= GlobalContext().get_showdict()
            logger.info(f"查看全局变量的值：{dic}")
            sql = Template(mysql).render(dic)
            logger.info(f'tempalte替换sql中变量后的sql语句：{sql}')
            value = db.select_db(sql)
            GlobalContext().set_dict({v[0]:value })
            logger.info(f'执行sql：{sql}并赋值变量{v[0]}存储全局变量成功！')

# from string import Template
# def a():
#     str = 'SELECT messageid FROM user_operation_userleavingmessage where id =${messageid}'
#     dic ={'messageid': 144723}
#     sql1 = Template(str).substitute(dic)
#     print(sql1)
# a()
    # def assert_text_comparators(self,**kwargs):
    #     comparators = {
    #         '>': lambda a, b: a > b,
    #         '<': lambda a, b: a < b,
    #         '==': lambda a, b: a == b,
    #         '>=': lambda a, b: a >= b,
    #         '<=': lambda a, b: a <= b,
    #         '!=': lambda a, b: a != b,
    #     }
    #
    #     message = kwargs.get('MESSAGE', None)
    #     if kwargs['OP_STR'] not in comparators:
    #         raise ValueError(f"没有该操作方式: {kwargs['OP_STR']}")
    #
    #     if not comparators[kwargs['OP_STR']](kwargs['VALUE'], kwargs["EXPECTED"]):
    #
    #         if message:
    #             raise AssertionError(message)
    #         else:
    #             raise AssertionError(f"{kwargs['VALUE']} {kwargs['OP_STR']} {kwargs['EXPECTED']} 失败")
    #
def a():
    comparators = {
        '>': lambda a, b: a > b,
        '<': lambda a, b: a < b,
        '==': lambda a, b: a == b,
        '>=': lambda a, b: a >= b,
        '<=': lambda a, b: a <= b,
        '!=': lambda a, b: a != b,
    }
    b = '>'
    try:
        if b in comparators:
            c = comparators[b]
            print(c(2,1))
            print(c(1,2))
    except Exception as e:
        raise e

a()
